package com.weixin.paleituo.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

import com.weixin.paleituo.base.ActivityLifeCycleEvent;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.bean.VersionBean;
import com.weixin.paleituo.eventbus.VersionEvent;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.rxjava.Api;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.FileUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import io.reactivex.Observable;
import io.reactivex.subjects.PublishSubject;

/**
 * 版本升级
 * 
 * @author leihuajie
 * 
 */
public class AppVersionUpdate {

	private Context context;
	private boolean isFirst = true;// true 表示从 main 进入 false 表示从设置进入
	private final int NEW_VERSION = 1;
	private final int NO_NEW_VERSION = -1;
	private final int UPDATE_PRO = 2;
	private final int UPDATE_COMPLETE = 3;
	private final int LOAD_ERROR = 4;
	private final int ACCESS_ERROR=5;
	private long length;
	private View view;
	private PublishSubject<ActivityLifeCycleEvent> mLifecycleSubject;
	private VersionUpdatePopuwindow popu;
	private String mId;
	private String apkname="shushe.apk";
	private VersionBean mVersionBean;
	private long mPrice;

	/**
	 * 获取弹框
	 * @return
	 */
	public VersionUpdatePopuwindow getPopu() {
		return popu;
	}

	public AppVersionUpdate(Context context, View view, PublishSubject<ActivityLifeCycleEvent> lifecycleSubject) {
		this.context = context;
		this.view = view;
		mLifecycleSubject = lifecycleSubject;
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			 if (msg.what == UPDATE_PRO) {// 更新下载进度
				 mPrice = msg.arg1;

				popu.setProgress((int) (mPrice * 100*10000 /  length));
			} else if (msg.what == UPDATE_COMPLETE) {// 下载完成
				popu.dismiss();
				update();

			} else if (msg.what == LOAD_ERROR) {
				Toast.makeText(context, "下载错误！", Toast.LENGTH_LONG).show();
				popu.dismiss();
			    if(mVersionBean!=null){
			    	File file = new File(FileUtils.APK_DIR, apkname);
			    	if(file!=null&&file.exists()){
			    		file.delete();
			    	}			    	
			    }

				 VersionEvent versionEvent=new VersionEvent();
			    versionEvent.setType(3);
				 EventBus.getDefault().post(versionEvent);
			}else if(msg.what==ACCESS_ERROR){
				Toast.makeText(context, "网络异常，请稍后再试！", Toast.LENGTH_LONG).show();
				 VersionEvent versionEvent=new VersionEvent();
				 versionEvent.setType(3);
				 EventBus.getDefault().post(versionEvent);
			}

		}
	};

	private String TAG = getClass().getSimpleName();



	/**
	 *
	 * @param isFirst true 一般为应用启动时调用，静默检查，false 将会把检查接口提示给用户
	 */
	public void checkVersionUpdate( final boolean isFirst) {
		this.isFirst = isFirst;
		int versionCode = UIUtils.getVersionCode(context);

		LogUtils.i(TAG,"当前版本号 ："+versionCode);
		Observable<StatusCode<VersionBean>> versionObservable = ApiUtils.getApi().checkVersion(versionCode + "");
		HttpUtil.getInstance().toSubscribe(versionObservable, new ProgressSubscriber<VersionBean>(context) {

			@Override
			protected void _onNext(StatusCode<VersionBean> t) {
				mVersionBean = t.getData();
				if (mVersionBean !=null){
					LogUtils.i(TAG,""+ mVersionBean.toString());
					mId = mVersionBean.getId();
					String coerce = mVersionBean.getCoerce();
					LogUtils.i(TAG,"是否强制更新 ："+coerce);
					if (!StringUtils.isEmpty(coerce) &&coerce.equals("1")){
						//强制更新
						doNewVersionUpdate(context,"1");// 有新版本

					}else if (!StringUtils.isEmpty(coerce)&& coerce.equals("0")){
						//非强制
						doNewVersionUpdate(context,"0");// 有新版本

					}else {
						if (!isFirst) {
							/*try {
								notNewVersionShow(context);// 没有新版本
							} catch (Exception e) {
								e.printStackTrace();
							}*/
							ToastUtils.makeText("当前已是最新版本，无需更新");
						}
					}

				}else {
					if (!isFirst) {
						/*try{
							notNewVersionShow(context);// 没有新版本
						}catch(Exception e){
							e.printStackTrace();
						}*/
						ToastUtils.makeText("当前已是最新版本，无需更新");
				}


			}

		}

			@Override
			protected void _onError(String message) {
				if(!isFirst){
					ToastUtils.makeText(message+"");
				}
			}},"",mLifecycleSubject,false,true);


	}

	private void notNewVersionShow(Context context) {
		popu = new VersionUpdatePopuwindow(context, false, 0);		
		popu.showAtLocation(view, Gravity.CENTER, 0, 0);
	}

	private void doNewVersionUpdate(final Context context, String isForce) {
		int isForcess = Integer.parseInt(isForce);
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			FileUtils.APK_DIR = Environment.getExternalStorageDirectory()
					.getAbsolutePath() + "/shushe/apks";
			File apkDir=new File(FileUtils.APK_DIR);
			if(!apkDir.exists()){
				apkDir.mkdirs();
			}
			popu = new VersionUpdatePopuwindow(context, true, Integer.parseInt(isForce));
			popu.showAtLocation(view, Gravity.CENTER, 0, 0);
			if (isForcess == 1) {
				downFile((Api.isRelease?Api.baseUrl:Api.testBaseUrl)+"shushe/version/export?id="+mId);
			} else {
				popu.setOnClick(new OnClick() {
					@Override
					public void onClick() {
						downFile((Api.isRelease?Api.baseUrl:Api.testBaseUrl)+"shushe/version/export?id="+mId);
					}
				});
			}
		}else{
			if(!isFirst){
				Toast.makeText(context,"本地存储设备异常，无法下载保存！！", Toast.LENGTH_LONG).show();
			}
		}
	}

	private void downFile(final String url) {
		new Thread() {
			public void run() {
				URL url2 = null;
				try {
					url2 = new URL(url);

					HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
					conn.setConnectTimeout(5000);
					conn.setRequestMethod("GET");

					conn.setRequestProperty("Accept-Encoding", "identity");
					conn.connect();
					/*if (conn.getResponseCode() == 200) {
   					maxLength = conn.getContentLength();
   					mPbar.setMax(maxLength);
   					InputStream is = conn.getInputStream();  */
					if (conn.getResponseCode()==200){
						length=		conn.getContentLength();
						LogUtils.i(TAG,"文件长度 ："+length);
						InputStream is = conn.getInputStream();
						File file = new File(FileUtils.APK_DIR, apkname);

						if(file!=null&&file.exists()){
							//本地已经存在文件
							if(file.length()==length){
								file.delete();
								/*Message message = handler.obtainMessage();
								message.what = UPDATE_COMPLETE;
								handler.sendMessage(message);
								return;*/
							}else{
								file.delete();
							}
						}else{
							//处理文件夹下的.apk文件
							File folder=new File(FileUtils.APK_DIR);
							File[] files=folder.listFiles(new FileFilter() {

								@Override
								public boolean accept(File pathname) {
									// TODO Auto-generated method stub
									return pathname.isFile();
								}
							});

							for(File file2:files){
								if(file2.getName().endsWith(".apk")){
									file2.delete();
								}
							}

						}


						FileOutputStream fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[5120];
						int ch = -1;
						int count = 0;
						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);
							count += ch;
							Message message = handler.obtainMessage();
							message.what = UPDATE_PRO;
							message.arg1 = count/10000;

							handler.sendMessage(message);


							LogUtils.i("yichao 当前下载 总数 ： ",count+"");
						}
						fileOutputStream.flush();
						fileOutputStream.close();
						is.close();
						Message message = handler.obtainMessage();
						message.what = UPDATE_COMPLETE;
						handler.sendMessage(message);
					}


				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (ProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}


	/*			HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				get.setHeader("Accept-Encoding", "identity");
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					length = entity.getContentLength();
					InputStream is = entity.getContent();
									
					File file = new File(FileUtils.APK_DIR, apkname);
					
					if(file!=null&&file.exists()){
						//本地已经存在文件
						if(file.length()==length){
							Message message = handler.obtainMessage();
							message.what = UPDATE_COMPLETE;
							handler.sendMessage(message);
							return;
						}else{
							file.delete();
						}
						
					}else{
						//处理文件夹下的.apk文件
						File folder=new File(FileUtils.APK_DIR);
						File[] files=folder.listFiles(new FileFilter() {
							
							@Override
							public boolean accept(File pathname) {
								// TODO Auto-generated method stub
								return pathname.isFile();
							}
						});
						
						for(File file2:files){
							if(file2.getName().endsWith(".apk")){
								file2.delete();
							}
						}
						
					}
					
					FileOutputStream fileOutputStream = new FileOutputStream(file);
					byte[] buf = new byte[5120];
					int ch = -1;
					int count = 0;
					while ((ch = is.read(buf)) != -1) {
						fileOutputStream.write(buf, 0, ch);
						count += ch;
						Message message = handler.obtainMessage();
						message.what = UPDATE_PRO;
						message.arg1 = count;
						handler.sendMessage(message);							
					}
					fileOutputStream.flush();
					fileOutputStream.close();
					is.close();
					Message message = handler.obtainMessage();
					message.what = UPDATE_COMPLETE;
					handler.sendMessage(message);
				} catch (Exception e) {
					Message message = handler.obtainMessage();
					message.what = LOAD_ERROR;
					handler.sendMessage(message);
					e.printStackTrace();
				}*/
			}
		}.start();
	}

	public interface OnClick {
		void onClick();
	}

	// 重新安装应用
	@SuppressLint("InlinedApi")
	@SuppressWarnings("deprecation")
	private void update() {

		try {
String apkPath=FileUtils.APK_DIR+"/"+apkname;
		if (context == null || TextUtils.isEmpty(apkPath)) {
			return;
		}


		File file = new File(apkPath);
		Intent intent = new Intent(Intent.ACTION_VIEW);

		//判读版本是否在7.0以上
		if (Build.VERSION.SDK_INT >= 24) {
			//provider authorities
			Uri apkUri = FileProvider.getUriForFile(context, "com.weixin.paleituo", file);
			//Granting Temporary Permissions to a URI
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
		} else {
			intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
		}
		intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
		intent.putExtra(Intent.EXTRA_ALLOW_REPLACE, true);
		intent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME, context.getApplicationInfo().packageName);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
			LogUtils.e(TAG,e.toString());
		}
	}

}
